﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QianBuo.Lottery.Web.Models.Login;
using Code.BLL;
using Code.Models;
using QianBuo.Lottery.Web.Commen;
using System.Web.Security;
using QianBuo.Lottery.Web.Models;
using System.Security.Cryptography;
using Code.Commen;
using System.Text.RegularExpressions;

namespace QianBuo.Lottery.Web.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        public ActionResult Index()
        {
            var CM = CacheManage.Ratio;
            var WM = CacheManage.WinModel;

            LoginModel model = new LoginModel
            {
                Ratios = new ModelNameValue<double, string>(CM.Values.Where(p => p.State == (short)ConsumeRatioState.Normal).OrderByDescending(p => p.Ratio).ToNameValue(p => (double)p.Ratio, p => p.Name)),
                WinModels = new ModelNameValue<int, string>(WM.Values.Where(p => p.State == (short)WinMoneyModelState.Normal).ToNameValue(p => p.ID, p => p.Name))

            };
            if (model.Show == false)
            {
                model.Show = false;
            }
            else
            {
                model.Show = true;
            }

            return View(model);
        }


        [HttpPost]
        [MultiButton(Name = "WinModel", Argument = "WinModel")]
        public ActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Show == true)
                {
                    if (model.CheckCode == null)
                    {
                        ModelState.AddModelError("CheckCode", "请输入验证码");
                    }
                    else
                    {
                        if (!model.CheckCode.Equals(TempData["Login"] as string, StringComparison.CurrentCultureIgnoreCase))
                            ModelState.AddModelError("CheckCode", "验证码不正确");
                        else
                        {
                            UserManage um = new UserManage();
                            Guid? uid;
                            LoginResult result;
                            LoginLog ll = null;
                            try
                            {
                                ll = um.Select<LoginLog, LoginLog>(s => s.Where(p => p.Users.LoginName == model.LoginName && p.LoginResult == (short)LoginResult.Normal).OrderByDescending(p => p.LoginTime).FirstOrDefault());
                                result = um.UserLogin(model.LoginName, model.LoginPwd, Request.UserHostAddress, out uid);
                                var win = PlayTypeOptionManage.SelectIdFromPlayTypeOption((Guid)uid.Value);
                                if (win == null)
                                {
                                    ViewData["LoginResult"] = Url.Action("Index").Redirect("对不起，您当前不拥有任何模式，请联系上级！");
                                    return View(model);
                                }
                            }
                            catch (AppException e)
                            {
                                ModelState.AddModelError("LoginError", e.Message);
                                return View(model);
                            }
                            if (result == LoginResult.PWDError)
                            {
                                model.Num++;
                                if (model.Num > 2 || model.Num == 2)
                                {
                                    model.Show = true;
                                }
                            }
                            if (result == LoginResult.Normal)
                            {
                                CommenManage<Users> cm = new CommenManage<Users>();
                                var u = cm.Select(s => s.Where(p => p.ID == uid.Value).Select(p => new { p.UserType, p.Account.Balance, p.Account.FreezeMoney, p.State }).FirstOrDefault());

                                var aus = System.Configuration.ConfigurationManager.GetSection("system.web/authentication") as System.Web.Configuration.AuthenticationSection;
                                if (aus != null)
                                {
                                    var str = string.Format("LoginID:{0}&WinModel:{1}&Ratio:{2}&Roles:User{3}&Them:{4}", uid, model.WinModel, model.Ratio, u.UserType == (short)UserType.Surrogate ? ",Surrogate" : "", "");
                                    FormsAuthenticationTicket tick = new FormsAuthenticationTicket(2, str, DateTime.Now, DateTime.Now.AddMinutes(aus.Forms.Timeout.TotalMinutes), false, "");
                                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tick));
                                    Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                                    Response.Cookies.Add(cookie);
                                }

                                Session["Login_Uid"] = uid;

                                var user = Global.OnLineUsers[uid.Value];
                                if (user != null)
                                {
                                    user.SessionID = Session.SessionID;
                                    if (ll == null || ll.LoginIP != Request.UserHostAddress)
                                    {
                                        string str = string.Format("<script>alert('您的账号已在:{1}登录\\r\\n请尽快修改密码！');location.href='{0}';</script>", Request["returnUrl"] ?? Url.Action("", ""), user.LoginIP);
                                        return Content(str);
                                    }
                                }

                                if (Request["ReturnUrl"] != null)
                                {
                                    return Redirect(Request["ReturnUrl"]);
                                }

                                return RedirectToAction("", "");
                            }
                            ModelState.AddModelError("LoginError", result.GetName());
                        }
                    }
                }
                else
                {

                    UserManage um = new UserManage();
                    Guid? uid;
                    LoginResult result;
                    LoginLog ll = null;
                    try
                    {
                        ll = um.Select<LoginLog, LoginLog>(s => s.Where(p => p.Users.LoginName == model.LoginName && p.LoginResult == (short)LoginResult.Normal).OrderByDescending(p => p.LoginTime).FirstOrDefault());
                        result = um.UserLogin(model.LoginName, model.LoginPwd, Request.UserHostAddress, out uid);
                    }
                    catch (AppException e)
                    {
                        ModelState.AddModelError("LoginError", e.Message);
                        return View(model);
                    }
                    if (Session["num"] != null)
                    {
                        model.Num = (int)Session["num"];
                    }
                    if(result==LoginResult.PWDError || result==LoginResult.UnExist)
                    {
                        model.Num++;
                        Session["num"] = model.Num;
                        if (model.Num > 2)
                        {
                            model.Show = true;
                        }
                    }
                    
                    if (result == LoginResult.Normal)
                    {
                        CommenManage<Users> cm = new CommenManage<Users>();
                        var u = cm.Select(s => s.Where(p => p.ID == uid.Value).Select(p => new { p.UserType, p.Account.Balance, p.Account.FreezeMoney, p.State }).FirstOrDefault());

                        var aus = System.Configuration.ConfigurationManager.GetSection("system.web/authentication") as System.Web.Configuration.AuthenticationSection;
                        if (aus != null)
                        {
                            var str = string.Format("LoginID:{0}&WinModel:{1}&Ratio:{2}&Roles:User{3}&Them:{4}", uid, model.WinModel, model.Ratio, u.UserType == (short)UserType.Surrogate ? ",Surrogate" : "", "");
                            FormsAuthenticationTicket tick = new FormsAuthenticationTicket(2, str, DateTime.Now, DateTime.Now.AddMinutes(aus.Forms.Timeout.TotalMinutes), false, "");
                            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tick));
                            Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
                            Response.Cookies.Add(cookie);
                        }
                        
                        var win = PlayTypeOptionManage.SelectIdFromPlayTypeOption((Guid)uid.Value);
                        if (win==null)
                        {
                            ViewData["LoginResult"] = Url.Action("Index").Redirect("对不起，您当前不拥有任何模式，请联系上级！");
                            return View(model);
                        }
                        Session["Login_Uid"] = uid;

                        var user = Global.OnLineUsers[uid.Value];
                        if (user != null)
                        {
                            user.SessionID = Session.SessionID;
                            if (ll == null || ll.LoginIP != Request.UserHostAddress)
                            {
                                string str = string.Format("<script>alert('您的账号已在:{1}登录\\r\\n请尽快修改密码！');location.href='{0}';</script>", Request["returnUrl"] ?? Url.Action("", ""), user.LoginIP);
                                return Content(str);
                            }
                        }

                        if (Request["ReturnUrl"] != null)
                        {
                            return Redirect(Request["ReturnUrl"]);
                        }

                        return RedirectToAction("", "");
                    }
                    ModelState.AddModelError("LoginError", result.GetName());

                }
            }

            return View(model);
        }

        public JsonResult CheckLogin()
        {

            object obj = new { IsLogin = User.Identity.IsAuthenticated };
            //if (User.Identity.IsAuthenticated)
            //    obj = new { IsLogin=true };
            //else
            //    obj = new { IsLogin=false};
            return Json(obj, JsonRequestBehavior.AllowGet);
        }

        public FileContentResult CheckCode(string id)
        {
            var codebuild = new CheckCodeModel();
            string code = codebuild.CreateVerifyCode();
            var img = codebuild.CreateImageCode(code);
            var ms = new System.IO.MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            var bytes = ms.ToArray();
            ms.Dispose();
            img.Dispose();
            if (string.IsNullOrEmpty(id))
                id = "CheckCode";
            TempData[id] = code;
            return new FileContentResult(bytes, "image/Jpeg");
        }

        #region 找回密码
        public ActionResult FindPwd()
        {
            return View(new FindPwdModel());
        }

        public JsonResult SendKey(string loginName, string email)
        {
            var msg = "";
            if (!string.IsNullOrEmpty(loginName))
            {
                var person = new UserManage().Select(s => s.Where(p => p.LoginName == loginName).Select(p => p.Person).FirstOrDefault());
                if (person == null)
                    msg = "没有找到指定的用户，请重新输入。";
                else if (string.IsNullOrEmpty(person.Email))
                    msg = "当前用户没有设置安全邮箱，请和管理员联系!";
                else if (!person.Email.Equals(email))
                    msg = "安全邮箱不正确!";
                else
                {
                    var key = MD5.Create().ComputeHash(Guid.NewGuid().ToString());
                    new Jmail().Send(person.Email, "找回密码", "您找回密码的密钥是:<br/>" + key, true);
                    msg = "密钥已发送到您的安全邮箱，请查收。";
                    TempData["FindPwdKey"] = key;
                }
            }
            else
                msg = "请输入用户名";
            return Json(new { msg }, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        [MultiButton(Name = "btnOk")]
        [ActionName("FindPwd")]
        public ActionResult Update(FindPwdModel model)
        {
            if (ModelState.IsValid)
            {
                if (!model.RegestCode.Equals(TempData["FinPwd"] as string, StringComparison.CurrentCultureIgnoreCase))
                {
                    ModelState.AddModelError("RegestCode", "验证码输入不正确");
                    return View(model);
                }
                var key = TempData["FindPwdKey"];
                if (key == null)
                {
                    ViewData["msg"] = "您先获取密钥。".AlertOffPage();
                    return View(model);
                }
                if (key.ToString() != model.InputKey)
                {
                    ViewData["msg"] = "密钥输入错误，请重新输入!".AlertOffPage();
                    TempData["FindPwdKey"] = key;
                    return View(model);
                }
                var count = new UserManage().UpdateLoginPwd(model.LoginName, model.NewPwd);
                if (count > 0)
                    ViewData["msg"] = "密码修改成功".AlertOffPage() + Url.Action("Index").Redirect();
                else
                {
                    ViewData["msg"] = "操作失败，请重新操作!".AlertOffPage();
                    TempData["FindPwdKey"] = key;
                }
            }
            return View(model);
        }
        #endregion
    }
}
